define(['maybe', 'jquery','app/utils'], (M, $, U) => {
  'use strict';

  (function start() {
    const maybe_id = M.maybe(new URLSearchParams(window.location.search).get('id'))

    M.map(id => {
      $('#buy-btn').on('click',buy_fn(id))
    },maybe_id)

    M.map(it => M.map(render_food, it), M.map(get_food_detail, maybe_id))
  }())

  //get_food_detail : id -> Maybe Food
  function get_food_detail(id) {
    let result = null
    $.get({
      url: '/user-end/food/'+id,
      async: false,
      success: (res) => {
        if(U.is_res_ok(res)){
          result = U.result(res)
        }else{
          alert('获取菜品信息出错了: '+U.error(res));
        }
      },
    })
    return M.maybe(result)
  }

  //render_food : Food -> ()
  function render_food(food) {
    $('#name').text(food.name)
    $('#desc').text(food.desc)
    $('#price').text(food.price)
  }

  function buy_fn(id){
    return () => {
      // alert('购买了id: ' + id)
      $.post({
        url: '/user-end/orders',
        data: {id}
      }).then(res => {
        if(U.is_res_ok(res)){
          alert('购买成功')
        }else{
          alert('购买失败: ' + U.error(res))
        }
      },err => {
        alert('服务器响应出错')
      })
    }
  }
});